package com.jlnk.newdemo.model;

import com.jlnk.newdemo.entity.NewsEntity;
import com.jlnk.newdemo.entity.NewsDetailEntity;
import com.jlnk.newdemo.service.NewsService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsModel {
    private static final String API_KEY = "6cbcdb4250c543fc38a812cce2026a31";
    private static final String BASE_URL = "http://v.juhe.cn/toutiao/";

    public interface NewsListCallback {
        void onSuccess(List<NewsEntity> newsList);
        void onFailure(String message);
    }
    public void getNewsList(String category, final NewsListCallback callback) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        NewsService service = retrofit.create(NewsService.class);
        service.getNewsList(category, API_KEY).enqueue(new Callback<NewsDetailEntity>() {
            @Override
            public void onResponse(Call<NewsDetailEntity> call, Response<NewsDetailEntity> response) {
                if (response.isSuccessful() && response.body() != null) {
                    NewsDetailEntity newsResponse = response.body();
                    if (newsResponse.getError_code() == 0 && newsResponse.getResult() != null) {
                        List<NewsEntity> newsList = newsResponse.getResult().getData();
                        callback.onSuccess(newsList);
                    } else {
                        callback.onFailure(newsResponse.getReason());
                    }
                } else {
                    callback.onFailure(response.message());
                }
            }

            @Override
            public void onFailure(Call<NewsDetailEntity> call, Throwable t) {
                callback.onFailure(t.getMessage());
            }
        });
    }
}